﻿// JScript File
function contrlevnt_handleEvent(pageid,targetcontrol,expression,contrlevnt_action,rowId,srcContrl,trigrValues)
{
	switch(contrlevnt_action.toLowerCase())
	{
		case "disable":
			break;
		case "enable":
			break;
		case "sv"://set value
			if (rowId != "") rowId = "_" + rowId;
			trigrValues = $("<div/>").html(trigrValues).text();			
			contrlevnt_processSetValue(expression,pageid,rowId,targetcontrol,srcContrl,trigrValues);
			break;
	}
	return true;
}
function contrlevnt_processSetValue(expression,pageid,rowId,targetcontrol,srcContrl,trigrValues)
{
    try
    {
        if (expression.indexOf('$[')<0)
        {
            contrlevnt_processNormalValues(expression,pageid,rowId,targetcontrol,false,trigrValues);
        }
        else
        {   
            if (srcContrl.id.match("_"+targetcontrol+"$")) return;//return if the expression is string based and the soure cand target are same.
            contrlevnt_getRelatedTableInfo(expression,pageid,srcContrl,rowId,targetcontrol,trigrValues);
        }
    }
    catch(ExcAll){}
}
function contrlevnt_processNormalValues(expression,pageid,rowId,targetcontrol, hasFieldInfo,trigrValues)
{
    try
    {
        expression = contrlevnt_parseExpression(expression,pageid,rowId);
        //alert(expression);
	    var exprOutput = contrlevnt_evaluvate(expression,hasFieldInfo);
	    var tempTargetcontrol = "ctl00_ContentPlaceHolder3_" + pageid +"_"+ targetcontrol+rowId;
	    //document.body.appendChild(document.createTextNode(tempTargetcontrol + "</br>"));
	    if (document.getElementById(tempTargetcontrol)!=null)//fill value for multiple records page (invoice-line like)
	    {
		    if (contrlevnt_checkIfAllowedValue(contrlevnt_getValue(document.getElementById(tempTargetcontrol)),trigrValues))
		        contrlevnt_setValue(document.getElementById(tempTargetcontrol),exprOutput);				
    //		if (document.getElementById("ctl00_ContentPlaceHolder3_total_" + pageid +"_"+ targetcontrol)!=null)//to trigger total events
    //		{					
    //			document.getElementById(tempTargetcontrol).onchange();
    //		}
	    } 
	    tempTargetcontrol = "ctl00_ContentPlaceHolder3_txt_" + pageid +"_"+ targetcontrol;
	    if (document.getElementById(tempTargetcontrol)!=null)//fill for lookup fields
	    {
	        if (contrlevnt_checkIfAllowedValue(contrlevnt_getValue(document.getElementById(tempTargetcontrol)),trigrValues))
		        contrlevnt_setValue(document.getElementById(tempTargetcontrol),exprOutput);
        }
        else
        {
	        //document.body.appendChild(document.createTextNode(tempTargetcontrol + "</br>"));
	        tempTargetcontrol = "ctl00_ContentPlaceHolder3_" + pageid +"_"+ targetcontrol;
	        if (document.getElementById(tempTargetcontrol)!=null)//fill for non lookup field
	        {
	            if (contrlevnt_checkIfAllowedValue(contrlevnt_getValue(document.getElementById(tempTargetcontrol)),trigrValues))
		            contrlevnt_setValue(document.getElementById(tempTargetcontrol),exprOutput);
            }
        }
    }
    catch(ExcNormal){}
}
function contrlevnt_checkIfAllowedValue(targetValue,trigrValues)
{
    var ret = true;
    if (trigrValues=="") return ret;
    ret = false;
    try
    {
        var trigrValuesArr = trigrValues.split('|');
        for(var j=0;j<trigrValuesArr.length;j++)    {
            if (targetValue==trigrValuesArr[j])        {
                ret= true;
                break;
            }
        }
    }
    catch(Exc){
        ret=true;
    }
    return ret;
}
function contrlevnt_getRelatedTableInfo(exprsn, pgid, srcContrl,rowId,targetcontrol,trigrValues)
{
    try
    {
        if (exprsn.indexOf('$[')<0) return exprsn;
        var retStr = contrlevnt_getTablesFieldsJSON(exprsn);
        retStr += '"source":{"pg":"Page1","ctrl":"Control1","value":"Value1","hvalue":"Value2"}}';
        retStr = retStr.replace("Page1",pgid);
        //ctl00_ContentPlaceHolder3_txt_p_control_events_test
        var srcControlReal = srcContrl.id.replace("ctl00_ContentPlaceHolder3_"+pgid+"_","");
        srcControlReal = srcControlReal.replace("ctl00_ContentPlaceHolder3_txt_"+pgid+"_","");    
        var srcControlhiddenvalue = document.getElementById(srcContrl.id).value;//get default value
        if (document.getElementById("ctl00_ContentPlaceHolder3_"+pgid+"_" + srcControlReal)!=null)//if textbox read from hidden
            srcControlhiddenvalue = document.getElementById("ctl00_ContentPlaceHolder3_"+pgid+"_" + srcControlReal).value;
        retStr = retStr.replace("Control1",srcControlReal);
        if (document.getElementById(srcContrl.id).value.length==0) srcControlhiddenvalue = ""; //removes the vaue if the value is removed from textbox, while hidden control has it.  
        //alert(srcContrl.id);    alert(document.getElementById(srcContrl.id).value);
        retStr = retStr.replace("Value1",document.getElementById(srcContrl.id).value.replace(/"/g, "\\\""));
        retStr = retStr.replace("Value2",srcControlhiddenvalue);
        //if (document.getElementById(srcContrl.id).value.length>0 || srcControlhiddenvalue.length>0)//checks for valid source
        {
             $.ajax({ url: "mb_ajaxhandler.aspx" , cache:false, 
             data: "action=ctrlevnt_fetch&data=" + escape(retStr),
             beforeSend: function() { contrlevnt_enabledisable(true,targetcontrol,pgid); },
             success: function(resp) { 
                //document.body.appendChild(document.createTextNode(resp));
                contrlevnt_processRelatedValues(resp,exprsn,pgid,rowId,targetcontrol,trigrValues); 
             },
             complete: function() { contrlevnt_enabledisable(false,targetcontrol,pgid); },
             error: function(resp) { 
                //alert("error"); 
                contrlevnt_enabledisable(false,targetcontrol,pgid);
             }
             });   
         }  
        //return exprsn;
    }
    catch(ExcRelated)
    {
        contrlevnt_enabledisable(false,targetcontrol,pgid);
    }
}
function contrlevnt_enabledisable(flg,targetcontrol,pageid)
{
    if (flg==true)
    {
        $("input:button[id*=_btnSave],input:submit[id*=_btnSave],input:button[id*=_btnReset]").attr('disabled', 'disabled');
        //$("#" + "ctl00_ContentPlaceHolder3_"+pageid+"_"+targetcontrol).css('backgroundRepeat','no-repeat');
        //$("#" + "ctl00_ContentPlaceHolder3_"+pageid+"_"+targetcontrol).css('backgroundPosition','right');
        $("#" + "ctl00_ContentPlaceHolder3_txt_"+pageid+"_"+targetcontrol).css({backgroundImage:'url(Images/load.gif)',backgroundRepeat:'no-repeat',backgroundPosition:'right'});
        $("#" + "ctl00_ContentPlaceHolder3_"+pageid+"_"+targetcontrol).css({backgroundImage:'url(Images/load.gif)',backgroundRepeat:'no-repeat',backgroundPosition:'right'});
    }
    else
    {
        $("#" + "ctl00_ContentPlaceHolder3_txt_"+pageid+"_"+targetcontrol).css('backgroundImage','none');
        $("#" + "ctl00_ContentPlaceHolder3_"+pageid+"_"+targetcontrol).css('backgroundImage','none');
        $("input:button[id*=_btnSave],input:submit[id*=_btnSave],input:button[id*=_btnReset]").removeAttr('disabled');
    }    
}
function contrlevnt_processRelatedValues(resp,expression,pageid,rowId,targetcontrol,trigrValues)
{
    //alert(resp);
    var myRespObject = eval('(' + resp + ')');
    for(var i=0;i<myRespObject.targets.length;i++)
    {
        var string2replace= "$[" + myRespObject.targets[i].tb  + "." + myRespObject.targets[i].fl + "]$";
        var value2replace= myRespObject.targets[i].value=="" ? "" : myRespObject.targets[i].value;        
        value2replace= value2replace==null ? "" : value2replace;        
        expression = expression.replace(string2replace,value2replace);                
    }
    //alert(expression);
    contrlevnt_processNormalValues(expression,pageid,rowId,targetcontrol,true,trigrValues)
}
function contrlevnt_getTablesFieldsJSON(expressn)
{
    if (expressn.indexOf('$[')<0) return '';
    var retString="";var tempStr='';
    while (expressn.indexOf('$[')>-1)
    {
        tempStr='{"tb": "Table1", "fl": "Field1"},';
        var start = expressn.indexOf('$[');
        var end = expressn.indexOf(']$');
        var temp = expressn.substring(start,end+2);
        tempStr = tempStr.replace("Table1",temp.split('.')[0].replace('$[',''));
        tempStr = tempStr.replace("Field1",temp.split('.')[1].replace(']$',''));
        retString += tempStr;
        expressn = expressn.replace(temp,'');
    }
    return '{"targets": [' + retString.substring(0,retString.length-1) + '],';
}
function contrlevnt_parseExpression(Expr, pageId,rowId)
{
	var elem = document.getElementById('aspnetForm').elements;
    for(var i = 0; i < elem.length; i++)
    {
		var elemId = elem[i].id;
		var text2beReplaced = "";
		if (elemId.indexOf("ctl00_ContentPlaceHolder3_"+pageId)>-1)
		{
			text2beReplaced = "ctl00_ContentPlaceHolder3_"+pageId+"_";
			text2beReplaced = "$" + elemId.substring(elemId.indexOf(text2beReplaced)+text2beReplaced.length).replace(rowId,"") +"$";
			if (Expr.indexOf(text2beReplaced)>-1 && text2beReplaced.length>2)
			{
				var value2beReplaced = contrlevnt_getValue(elem[i]);
				while (Expr.indexOf(text2beReplaced) > -1)//to replace all the characters
				{
					Expr = Expr.replace(text2beReplaced,value2beReplaced);
				}
			}
		}
	}
	return Expr;
}

function contrlevnt_evaluvate(Expr,hasFieldInfo)
{
    var ret="";
	try
	{
	    if (Expr=="") 
	        ret = "";
	    else
		    ret = eval(Expr);
		if (ret == NaN)
		    ret = eval("ret = " + Expr + ";");
		//alert(ret);
	}
	catch(ExEval)
	{
	    //alert(ExEval.message);
	    if (hasFieldInfo) ret = Expr;
	}
	return ret;
}

function contrlevnt_setValue(Contrl,controlValue)
{
	if (Contrl==null) return;
	if (Contrl.type=="select-one") 
	{   
	    var found = false;
		for(var i = 1; i < Contrl.options.length; i++) 
		{
			if(Contrl.options[i].value == controlValue) 
			{
				Contrl.selectedIndex = i;
				found = true;
				break;
			}
		}
		if (found==false)
		{
		    for(var i = 1; i < Contrl.options.length; i++) 
		    {
			    if(Contrl.options[i].text == controlValue) 
			    {
				    Contrl.selectedIndex = i;
				    found = true;
				    break;
			    }
		    }
		}
	}
	else if (Contrl.type=="select-multiple") 
	{
		for(var i = 1; i < Contrl.options.length; i++) 
		{
			if(Contrl.options[i].value == controlValue) 
			{
				Contrl.options[i].selected == true
				break;
			}
		}
	}
	else if (Contrl.type=="checkbox")
	{
		Contrl.checked = Boolean(controlValue);
	}
	else
	{
		Contrl.value = controlValue;
	}
}

function contrlevnt_getValue(Contrl)
{
	if (Contrl==null) return "";
	var returnValue;
	if (Contrl.type=="select-one") 
	{   
		returnValue = Contrl.options[Contrl.selectedIndex].value;
	}
	else if (Contrl.type=="select-multiple") 
	{
		returnValue = null;
	}
	else if (Contrl.type=="checkbox")
	{
		returnValue = Boolean(Contrl.checked);
	}
	else
	{
		returnValue = Contrl.value;
	}
	return returnValue;
}